package cn.ronghuanet.auth.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 登录拦截器 判断当前有没有登录
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1 从请求头中获取token
        String token = request.getHeader("token");

        // 2 如果token为空,没有登录,返回错误信息给前端,并阻止运行
        if(StringUtils.isBlank(token)){
            response.getWriter().write("{\"success\":false,\"msg\":\"noLogin\"}");
            return false;
        }

        // 3 根据token作为key,去redis中查询登录信息
        Object loginUser = redisTemplate.opsForValue().get(token);

        // 4 如果登录信息为空,说明没有登录,返回错误信息给前端,并阻止运行
        if(Objects.isNull(loginUser)){
            response.getWriter().write("{\"success\":false,\"msg\":\"noLogin\"}");
            return false;
        }
        // 放行请求,去正常访问controller
        return true;
    }
}
